package config

import (
	"fmt"
	"os"
	"sync"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/platform/common"
	"github.com/gin-gonic/gin"
	"gopkg.in/yaml.v3"
)

// Config represents the application configuration
type Config struct {
	Server struct {
		Port int    `yaml:"port"`
		Mode string `yaml:"mode"`
	} `yaml:"server"`

	Database struct {
		Host      string `yaml:"host"`
		Port      string `yaml:"port"`
		Username  string `yaml:"username"`
		Password  string `yaml:"password"`
		DBName    string `yaml:"dbname"`
		Charset   string `yaml:"charset"`
		ParseTime bool   `yaml:"parse_time"`
		Loc       string `yaml:"loc"`
	} `yaml:"database"`

	Redis struct {
		Host         string `yaml:"host"`
		Port         string `yaml:"port"`
		Password     string `yaml:"password"`
		DB           int    `yaml:"db"`
		PoolSize     int    `yaml:"pool_size"`
		MinIdleConns int    `yaml:"min_idle_conns"`
		MaxRetries   int    `yaml:"max_retries"`
		DialTimeout  int    `yaml:"dial_timeout"`
		ReadTimeout  int    `yaml:"read_timeout"`
		WriteTimeout int    `yaml:"write_timeout"`
		PoolTimeout  int    `yaml:"pool_timeout"`
		IdleTimeout  int    `yaml:"idle_timeout"`
		MaxConnAge   int    `yaml:"max_conn_age"`
	} `yaml:"redis"`

	MongoDB struct {
		Host           string `yaml:"host"`
		Port           string `yaml:"port"`
		Username       string `yaml:"username"`
		Password       string `yaml:"password"`
		Database       string `yaml:"database"`
		AuthSource     string `yaml:"auth_source"`
		MaxPoolSize    uint64 `yaml:"max_pool_size"`
		MinPoolSize    uint64 `yaml:"min_pool_size"`
		MaxIdleTime    int    `yaml:"max_idle_time"`
		ConnectTimeout int    `yaml:"connect_timeout"`
		SocketTimeout  int    `yaml:"socket_timeout"`
	} `yaml:"mongodb"`

	JWT struct {
		Secret    string `yaml:"secret"`
		ExpiresIn int    `yaml:"expires_in"` // 过期时间（小时）
	} `yaml:"jwt"`

	Email struct {
		Provider string `yaml:"provider"`
		Host     string `yaml:"host"`
		Port     int    `yaml:"port"`
		Username string `yaml:"username"`
		Password string `yaml:"password"`
		From     string `yaml:"from"`
		Template struct {
			Paths []string `yaml:"paths"`
		} `yaml:"template"`
		Outlook struct {
			ClientID     string `yaml:"client_id"`
			ClientSecret string `yaml:"client_secret"`
			TenantID     string `yaml:"tenant_id"`
			RefreshToken string `yaml:"refresh_token"`
		} `yaml:"outlook"`
		QQ struct {
			Username string `yaml:"username"`
			Password string `yaml:"password"`
		} `yaml:"qq"`
		Zoho struct {
			Username    string `yaml:"username"`
			Password    string `yaml:"password"`
			FromAddress string `yaml:"from_address"`
		} `yaml:"zoho"`
	} `yaml:"email"`

	Aliyun struct {
		AccessKeyID     string `yaml:"access_key_id"`
		AccessKeySecret string `yaml:"access_key_secret"`
		SmsSignName     string `yaml:"sms_sign_name"`
		SmsTemplateCode string `yaml:"sms_template_code"`
	} `yaml:"aliyun"`

	Logger struct {
		Level      string `yaml:"level"`
		Filename   string `yaml:"filename"`
		MaxSize    int    `yaml:"maxsize"`
		MaxAge     int    `yaml:"maxage"`
		MaxBackups int    `yaml:"maxbackups"`
	} `yaml:"logger"`

	CORS struct {
		AllowedOrigins   []string `yaml:"allowed_origins"`
		AllowedMethods   []string `yaml:"allowed_methods"`
		AllowedHeaders   []string `yaml:"allowed_headers"`
		ExposedHeaders   []string `yaml:"exposed_headers"`
		AllowCredentials bool     `yaml:"allow_credentials"`
		MaxAge           int      `yaml:"max_age"`
	} `yaml:"cors"`

	// PlatformSelection 平台选择配置
	PlatformSelection struct {
		Enabled bool `yaml:"enabled"` // 是否启用月份平台选择
		// 月份平台映射，key为月份(1-12)，value为平台名称("photonpay"或"hlpay")
		MonthlyPlatforms map[string]string `yaml:"monthly_platforms"`
		// 默认平台，当月份未配置时使用
		DefaultPlatform string `yaml:"default_platform"`
	} `yaml:"platform_selection"`

	PhotonPay struct {
		AppID              string `yaml:"app_id"`
		AppSecret          string `yaml:"app_secret"`
		MerchantPrivateKey string `yaml:"merchant_private_key"`
		PlatformPublicKey  string `yaml:"platform_public_key"`
		GatewayURL         string `yaml:"gateway_url"`
		Token              struct {
			ExpiresIn          int `yaml:"expires_in"`           // token过期时间（秒）
			RefreshBefore      int `yaml:"refresh_before"`       // 提前刷新时间（秒）
			MinRefreshInterval int `yaml:"min_refresh_interval"` // 最小刷新间隔（秒）
			MaxRetries         int `yaml:"max_retries"`          // 最大重试次数
			RetryInterval      int `yaml:"retry_interval"`       // 重试间隔（秒）
		} `yaml:"token"`
	} `yaml:"photonpay"`

	JuswayPay struct {
		Username    string `yaml:"username"`
		Password    string `yaml:"password"`
		TwoPassword string `yaml:"two_password"`
		GatewayURL  string `yaml:"gateway_url"`
		Timeout     int    `yaml:"timeout"`
	} `yaml:"juswaypay"`

	HlPay struct {
		ClientID       string `yaml:"clientid"`
		ClientKey      string `yaml:"clientkey"`
		ClientSecret   string `yaml:"clientSecret"`
		GatewayURL     string `yaml:"gateway_url"`
		RefreshTime    int    `yaml:"refresh_time"`
		MinRefreshTime int    `yaml:"min_refresh_time"`
	} `yaml:"hlPay"`

	FilePath string `yaml:"file_path"`

	// TimeZone 时区配置
	TimeZone struct {
		DefaultTimeZone  string `yaml:"default_timezone"`
		DatabaseTimeZone string `yaml:"database_timezone"`
		DisplayTimeZone  string `yaml:"display_timezone"`
	} `yaml:"timezone"`
}

var (
	GlobalConfig Config
	configOnce   sync.Once
)

// Init initializes the configuration
func Init() error {
	var err error
	configOnce.Do(func() {
		// Determine environment
		env := os.Getenv("APP_ENV")
		if env == "" {
			env = "development"
		}

		// Determine config file path
		configFile := "config/config.yaml"
		if env == "production" {
			configFile = "config/config.prod.yaml"
		}

		// Read config file
		data, err := os.ReadFile(configFile)
		if err != nil {
			err = fmt.Errorf("failed to read config file: %v", err)
			return
		}

		// Parse YAML
		if err := yaml.Unmarshal(data, &GlobalConfig); err != nil {
			err = fmt.Errorf("failed to parse config file: %v", err)
			return
		}

		// Set Gin mode
		gin.SetMode(GlobalConfig.Server.Mode)
	})
	return err
}

// GetConfig returns the global configuration instance
func GetConfig() *Config {
	return &GlobalConfig
}

// GetPlatformConfig returns the platform configuration
func GetPlatformConfig() *common.PlatformConfig {
	return &common.PlatformConfig{
		AppID:      GlobalConfig.PhotonPay.AppID,
		AppSecret:  GlobalConfig.PhotonPay.AppSecret,
		GatewayURL: GlobalConfig.PhotonPay.GatewayURL,
		PrivateKey: GlobalConfig.PhotonPay.MerchantPrivateKey,
		PublicKey:  GlobalConfig.PhotonPay.PlatformPublicKey,
	}
}

// GetHlPayConfig returns the hlPay platform configuration
func GetHlPayConfig() *common.PlatformConfig {
	return &common.PlatformConfig{
		AppID:      GlobalConfig.HlPay.ClientID,
		AppSecret:  GlobalConfig.HlPay.ClientSecret,
		GatewayURL: GlobalConfig.HlPay.GatewayURL,
	}
}

// GetCurrentMonthPlatform 获取当前月份应该使用的平台
func GetCurrentMonthPlatform() string {
	// 如果平台选择功能未启用，使用默认的单双月逻辑
	if !GlobalConfig.PlatformSelection.Enabled {
		month := time.Now().Month()
		if month%2 == 1 {
			return "hlpay"
		} else {
			return "photonpay"
		}
	}

	// 获取当前月份
	currentMonth := fmt.Sprintf("%d", time.Now().Month())

	// 查找当前月份的配置
	if platform, exists := GlobalConfig.PlatformSelection.MonthlyPlatforms[currentMonth]; exists {
		return platform
	}

	// 如果当前月份未配置，使用默认平台
	if GlobalConfig.PlatformSelection.DefaultPlatform != "" {
		return GlobalConfig.PlatformSelection.DefaultPlatform
	}

	// 如果默认平台也未配置，回退到单双月逻辑
	month := time.Now().Month()
	if month%2 == 1 {
		return "hlpay"
	} else {
		return "photonpay"
	}
}
